package net.mapbb.main;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.ConsoleMessage;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockMapActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.actionbarsherlock.view.Window;
import com.actionbarsherlock.widget.SearchView;
import com.androidquery.AQuery;
import com.androidquery.auth.FacebookHandle;
import com.androidquery.auth.TwitterHandle;
import com.androidquery.callback.AbstractAjaxCallback;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.gcm.GCMRegistrar;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.googlecode.androidannotations.annotations.AfterViews;
import com.googlecode.androidannotations.annotations.EActivity;
import com.googlecode.androidannotations.annotations.OnActivityResult;
import com.googlecode.androidannotations.annotations.ViewById;


@SuppressLint("SetJavaScriptEnabled")
@EActivity(R.layout.activity_main)
public class MainActivity extends SherlockMapActivity implements ActionBar.OnNavigationListener, ActionBar.TabListener {
	
	public static final int REQUEST_CODE_USER_LOGIN = 0;
	public static final int REQUEST_CODE_PUBLISH_POST = 1;
	
	public static final String TWITTER_CONSUMER_KEY = "8NuqZdLwJTG8ukYVTUqjTA";
	public static final String TWITTER_CONSUMER_SECRET = "CTG2Y3nJz77ZKjsBlttwzp8Ub1NqFGYWk8mD5RguTU";
	
	public static final String FACEBOOK_APP_ID = "269802973146426";
    public static final String FACEBOOK_PERMISSIONS = "read_stream,read_friendlists,manage_friendlists,manage_notifications,publish_stream,publish_checkins,offline_access,user_photos,user_likes,user_groups,friends_photos";
	
    public static final String GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile&redirect_uri=http://www.mapbb.net/google_auth_callback.html&response_type=token&client_id=1028919553090.apps.googleusercontent.com";

    
	public static final String EXTERNAL_STORAGE_URL_BASE = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ? "file://" + Environment.getExternalStorageDirectory() + "/" : null;
	public static final String ASSETS_URL_BASE = "file:///android_asset/";
//	public static final String SERVER_URL_BASE = "http://www.mapbb.net/";
	public static final String SERVER_URL_BASE = "http://192.168.1.101/";
	
	@ViewById(R.id.webViewMain) WebView webView;
	@ViewById(R.id.mapView) MapView mapView;
	@ViewById(R.id.buttonMapMode) ImageButton buttonMapMode;
	
	
    String[] tabsTxt;
    Menu menu;
    boolean loggedin;
    AQuery aq = new AQuery(this);
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setTheme(R.style.Theme_Sherlock);
		super.onCreate(savedInstanceState);
        //This has to be called before setContentView and you must use the
        //class in com.actionbarsherlock.view and NOT android.view
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
	}
	

	
	@AfterViews
	public void initialize2(){
		/*
		 * Google Cloud Messaging
		 */
		try{
			GCMRegistrar.checkDevice(this);
			GCMRegistrar.checkManifest(this);
			final String regID = GCMRegistrar.getRegistrationId(this);
			if (regID.equals("")) {
			  GCMRegistrar.register(this, GCMIntentService.SENDER_ID);
			} else {
			  Log.v(GCMIntentService.TAG, "Already registered. Registration id:" + regID);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
		
		/*
		 * google analytics
		 */
		EasyTracker.getInstance().setContext(this);
		
		/*
		 * action bar
		 */
        final ActionBar actionBar = getSupportActionBar();
        actionBar.setSubtitle(R.string.not_logged_in);
        actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.ab_bg_black));
        
        tabsTxt = getResources().getStringArray(R.array.tabs_post);
        for (int i = 0; i < tabsTxt.length; i++) {
            ActionBar.Tab tab = getSupportActionBar().newTab();
            tab.setText(tabsTxt[i]);
            tab.setTabListener(this);
            actionBar.addTab(tab);
        }
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        
		/*
		 * web view
		 */
		webView.getSettings().setJavaScriptEnabled(true);
		webView.setBackgroundColor(0);
		webView.setVisibility(View.INVISIBLE);
		webView.setWebViewClient(new WebViewClient(){
			@Override
			public boolean shouldOverrideUrlLoading(WebView webView, String url) {
				if(url.startsWith(SERVER_URL_BASE)){
					webView.loadUrl(url);
				}else{
					startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
				}
				return true;
			}
			
			@Override
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
				Toast.makeText(getApplication(), R.string.msg_on_received_error, Toast.LENGTH_LONG).show();
			}
		});
		webView.setWebChromeClient(new WebChromeClient(){
			@Override
			public boolean onJsAlert(WebView view, String url, String message,JsResult result) {
				Toast.makeText(getApplication(), message, Toast.LENGTH_LONG).show();
				result.confirm();
				return true;
			}

			@Override
			public boolean onConsoleMessage(ConsoleMessage consoleMessage){
				Log.i("webView Main", consoleMessage.message());
				return true;
			}
		});
		
		
		/*
		 * map view
		 */
	    mapView.setBuiltInZoomControls(true);
        mapView.setClickable(true);  
        MapController mMapCtrl = mapView.getController();
        mMapCtrl.animateTo(new GeoPoint(39909230, 116397428));
        
        buttonMapMode.setOnClickListener(new OnClickListener() {  
        	@Override  
            public void onClick(View v) {
        		if(webView.getVisibility()==View.VISIBLE){
            		buttonMapMode.setImageResource(R.drawable.btn_show_list);
            		webView.setVisibility(View.INVISIBLE);
        		}else{
            		buttonMapMode.setImageResource(R.drawable.btn_show_map);
            		webView.setVisibility(View.VISIBLE);
            		webView.loadUrl(SERVER_URL_BASE + "content.html");
        		}
            }
        });
        
		if( getSharedPreferences("config",Context.MODE_PRIVATE).getBoolean("auto_login", false) ){
			popupWebContent(SERVER_URL_BASE + "login.html");
		}

	}
		
	public void verifyToken(String type, String token, String secret){
		aq.ajax(SERVER_URL_BASE + "login_3rd.service?type=" + type + "&token=" + token + "&secret=" + secret, JSONObject.class, new AjaxCallback<JSONObject>(){
			@Override
            public void callback(String url, JSONObject json, AjaxStatus status) {
				if(status.getCode() == 200){
					try{
						if(json.has("error")){
							showLoginFailed("");
						}else{
							getSupportActionBar().setSubtitle(getResources().getString(R.string.login_as) + json.getString("name"));
							loggedin = true;
							updateMenu();
						}										
					}catch(Exception e){
						e.printStackTrace();
					}
				}else{
					Log.i("ajax", "url:" + url);
					Log.i("ajax", "status:" + status.toString());
					showLoginFailed("");
				}
            }
		});
	}
	
	void showLoginFailed(String reason){
		Toast.makeText(getApplication(), getResources().getString(R.string.login_failed) + reason, Toast.LENGTH_SHORT).show();
	}
	
	@OnActivityResult(REQUEST_CODE_USER_LOGIN)
	void onUserLoginResult(int resultCode, Intent data) {
		if(resultCode==Activity.RESULT_OK && data != null){
			String type = data.getStringExtra("type");
			if(type.equals("google_auth")){
				if(data.getStringExtra("error") == null){
					verifyToken("google", data.getStringExtra("access_token"), "");
				}else{
					showLoginFailed(data.getStringExtra("error"));
				}
			}				
		}
	}

	@OnActivityResult(REQUEST_CODE_PUBLISH_POST)
	void onPublishPostResult(int resultCode, Intent data) {
		//TODO
	}
	
	@Override
	protected void onDestroy() {
		aq.dismiss();
		super.onDestroy();
	}


	@Override
	public void onStart() {
		EasyTracker.getInstance().activityStart(this);
		super.onStart();
	}

	@Override
	public void onStop() {
		EasyTracker.getInstance().activityStop(this);
		super.onStop();
	}
	
	public void updateMenu(){
		menu.getItem(0).setVisible(!loggedin);//login
		menu.getItem(1).setVisible(false);//register
		menu.getItem(2).setVisible(true);//publish
		menu.getItem(3).setVisible(loggedin);//profile
		menu.getItem(4).setVisible(loggedin);//message
		menu.getItem(5).setVisible(true);//my position
		menu.getItem(6).setVisible(true);//search
		menu.getItem(7).setVisible(true);//about
		menu.getItem(8).setVisible(loggedin);//logout
	}
	
	public void popupWebContent(String url){
		Intent intent = new Intent(MainActivity.this, PopupWebActivity_.class);
		intent.putExtra("url", url);
		startActivityForResult(intent, REQUEST_CODE_USER_LOGIN);
	}
	

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	this.menu = menu;
    	
    	SubMenu sm = menu.addSubMenu(R.string.menu_login);
        sm.add(R.string.menu_login_google);
        sm.add(R.string.menu_login_facebook);
        sm.add(R.string.menu_login_twitter);
        sm.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

    	menu.add(R.string.menu_register)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

    	menu.add(R.string.menu_publish)
        .setIcon(R.drawable.ic_compose)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
    	
    	menu.add(R.string.menu_profile)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

    	menu.add(R.string.menu_message)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

    	menu.add(R.string.menu_my_position)
        .setIcon(R.drawable.ic_my_location)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
    	
        //Create the search view
        SearchView searchView = new SearchView(getSupportActionBar().getThemedContext());
        searchView.setQueryHint(getResources().getString(R.string.hint_menu_search));
        
        menu.add(R.string.menu_search)
        .setIcon(R.drawable.ic_search)
        .setActionView(searchView)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);

    	menu.add(R.string.menu_about)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        
    	menu.add(R.string.menu_logout)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

    	updateMenu();
    	
        return super.onCreateOptionsMenu(menu);
    }

	
    @Override
	public void onBackPressed() {
    	if(webView.getVisibility()==View.VISIBLE && webView.canGoBack()){
			webView.goBack();
    	}else{
    		super.onBackPressed();
    	}
	}
    
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {

    	if(item.getTitle().equals(getResources().getString(R.string.menu_login_google))){
    		popupWebContent(GOOGLE_AUTH_URL);
    	}else if(item.getTitle().equals(getResources().getString(R.string.menu_login_facebook))){
			FacebookHandle handle = new FacebookHandle(this, FACEBOOK_APP_ID, FACEBOOK_PERMISSIONS) {
				@Override
				public boolean expired(AbstractAjaxCallback<?, ?> cb, AjaxStatus status) {
					// custom check if re-authentication is required
					if (status.getCode() == 401) {
						return true;
					}
					return super.expired(cb, status);
				}
			};
			aq.auth(handle).ajax("https://graph.facebook.com/me/feed", JSONObject.class, new AjaxCallback<JSONObject>(){
				@Override
	            public void callback(String url, JSONObject json, AjaxStatus status) {
			    	Log.i("TEST", "facebook callback!!!");
	            }
			});
        }else if(item.getTitle().equals(getResources().getString(R.string.menu_login_twitter))){
        	TwitterHandle handle = new TwitterHandle(this, TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET){
            	@Override
                protected void authenticated(String secret, String token) {
            		verifyToken("twitter", token, secret);
                }
            };
        	handle.authenticate(true);
    	}else if(item.getTitle().equals(getResources().getString(R.string.menu_register))){
    		popupWebContent(SERVER_URL_BASE + "agreement.html");
    	}else if(item.getTitle().equals(getResources().getString(R.string.menu_publish))){
    		popupWebContent(SERVER_URL_BASE + "publish.html");
    	}else if(item.getTitle().equals(getResources().getString(R.string.menu_profile))){
    		popupWebContent(SERVER_URL_BASE + "profile.html");
    	}else if(item.getTitle().equals(getResources().getString(R.string.menu_message))){
    	}else if(item.getTitle().equals(getResources().getString(R.string.menu_logout))){
    		CookieSyncManager.createInstance(this); 
		    CookieManager cookieManager = CookieManager.getInstance();
		    cookieManager.removeAllCookie();

		    getSharedPreferences("config",Context.MODE_PRIVATE).edit().putBoolean("auto_login", false).commit();
			loggedin = false;
			updateMenu();
		    getSupportActionBar().setSubtitle(R.string.not_logged_in);

			Toast.makeText(getApplication(), R.string.logout_successfully, Toast.LENGTH_SHORT).show();
    	}else if(item.getTitle().equals(getResources().getString(R.string.menu_my_position))){
    	}else if(item.getTitle().equals(getResources().getString(R.string.menu_search))){
    	}

		return true;
	}
	

	@Override
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
    	Toast.makeText(getApplication(), "item " + itemPosition + " clicked.", Toast.LENGTH_SHORT).show();
        return true;
    }
    
    @Override
    public void onTabReselected(Tab tab, FragmentTransaction transaction) {
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction transaction) {    	
    	if(buttonMapMode!=null){
        	buttonMapMode.setVisibility(tab.getPosition()==0 ? View.VISIBLE : View.INVISIBLE);    		
    	}
    	Toast.makeText(getApplication(), tab.getText(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction transaction) {
    }

}
